from rest_framework import serializers
from apps.goods.models import SKUImage
# 导入客户端模块
from fdfs_client.client import Fdfs_client
from apps.goods.utils import create_detail_html


class SKUImageSerialzier(serializers.ModelSerializer):
    class Meta:
        model = SKUImage
        fields = '__all__'

    # 重写保存业务实现图片的保存操纵
    def create(self, validated_data):
        # 生成fastDFS链接对象
        client = Fdfs_client(
            '/home/ubuntu/Desktop/meiduo_project/meiduo_mall/meiduo_mall/utils/fastdfs/client.conf')
        # 上传图片到fastDFS
        # 按照文件名上传
        # client.upload_appender_by_filename()
        # 前端传得的是文件数据所有需要按照二进制数据上传
        img = validated_data['image']
        res = client.upload_appender_by_buffer(img.read())
        # 判断是否上传成功
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError('图片上传失败')
        # 获取上传后的图片地址
        image_url = res['Remote file_id']
        # 获取sku表的对象
        sku = validated_data['sku']
        # 判断sku是否有默认图片 没有就将图片最为sku的默认图片
        if sku.default_image is None:
            sku.default_image = image_url
            sku.save()
        # 保存图片表
        image = SKUImage.objects.create(sku=sku, image=image_url)
        # 生成新的详情页页面
        create_detail_html(sku.id)
        return image

    # 重写更新业务实现图片的更新操纵
    def update(self, instance, validated_data):
        # 生成fastDFS链接对象
        client = Fdfs_client(
            '/home/ubuntu/Desktop/meiduo_project/meiduo_mall/meiduo_mall/utils/fastdfs/client.conf')
        # 上传图片到fastDFS
        # 按照文件名上传
        # client.upload_appender_by_filename()
        # 前端传得的是文件数据所有需要按照二进制数据上传
        img = validated_data['image']
        res = client.upload_appender_by_buffer(img.read())
        # 判断是否上传成功
        if res['Status'] != 'Upload successed.':
            raise serializers.ValidationError('图片上传失败')
        # 获取上传后的图片地址
        image_url = res['Remote file_id']
        # 更新数据
        instance.sku = validated_data['sku']
        instance.image = image_url
        instance.save()
        # 生成新的详情页页面
        create_detail_html(validated_data['sku'].id)
        return instance